<?php

namespace App\Http\Controllers\Admin;

use App\Master\Framework\Extend\DataUtil;
use App\Master\Framework\View\AdminData;
use App\Models\Admin\Framework\AdminSetupModel;
use App\Utils\AppResult;
use Illuminate\Support\Facades\Cache;

/**
 * Admin 模块父级
 * Module 接管 CURD 公共操作
 * Class ModuleController
 * @package App\Http\Controllers\Framework
 */
class ModuleController extends ParentController
{
    protected        $model;  // 在子类中赋值
    protected string $view         = '';    // 视图文件目录
    protected array  $params       = [];    // 请求参数
    protected array  $unset_fields = ['status'];    // 初始化隐藏字段
    protected int    $statusValue  = 2;    // 状态默认值
    protected string $isPost;              // 请求类型是否为POST

    public function __construct(array $attributes = [])
    {
        parent::__construct();
        $this->isPost = request()->isMethod('post');
        $this->params = request()->all();
    }

    /**
     * 列表页
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|string
     */
    public function index()
    {
        if ($this->isPost) {
            $params = $this->params;

            $query = $this->model;

            // 自动排序
            if ($orderBy = AdminData::orderBy()) {
                foreach ($orderBy as $order){
                    $query->orderBy($order['sort'], $order['orderBy']);
                }
            }

            if (!isset($params['page'])){
                $list = $query->where('is_delete', 0)->get();
            }else{
                $list = $query->where('is_delete', 0)->paginate($params['size'] ?? 15);
            }

            return AppResult::response200('success', $list);
        } else {
            return view($this->view);
        }
    }

    /**
     * 添加
     * @return string
     */
    public function insert()
    {
        $params = $this->params;

        // 初始化空数据
        $form               = DataUtil::field($params, $this->unset_fields);
        $form['status']     = $this->statusValue;
        $form['created_at'] = time();
        if (!$this->model->insert($form)) {
            return AppResult::response201('创建失败');
        }
        return AppResult::response200('创建成功');
    }

    /**
     * 修改
     * @return string
     */
    public function update()
    {
        $params = $this->params;
        if (empty($params['id'])) {
            return AppResult::response203('操作超时！');
        }

        // 初始化空数据
        $form               = DataUtil::field($params, array_merge(['is_system'], $this->unset_fields));
        $form['updated_at'] = time();
        if (!$this->model->where('id', $params['id'])->update($form)) {
            return AppResult::response201('操作失败');
        }
        return AppResult::response200('操作成功');
    }

    /**
     * 状态
     * @return string
     */
    public function status()
    {
        $params = $this->params;
        if (empty($params['id']) || !isset($params['status'])) {
            return AppResult::response203('操作超时！');
        }

        $form['status']     = $params['status'] == 1 ? 2 : 1;
        $form['updated_at'] = time();
        if (!$this->model->where('id', $params['id'])->update($form)) {
            return AppResult::response201('操作失败');
        }
        return AppResult::response200('操作成功');
    }

    /**
     * 删除
     * @return string
     */
    public function remove()
    {
        $params = $this->params;
        if (empty($params['id'])) {
            return AppResult::response203('操作超时！');
        }

        $form['is_delete']  = 1;
        $form['updated_at'] = time();
        if (!$this->model->where('id', $params['id'])->update($form)) {
            return AppResult::response201('操作失败');
        }
        return AppResult::response200('操作成功');
    }

    /**
     * 排序
     * @return string
     */
    public function rank()
    {
        $params = $this->params;
        if (!isset($params['id']) || !isset($params['sort'])) {
            return AppResult::response203('操作超时！');
        }

        $form['sort']       = $params['sort'];
        $form['updated_at'] = time();

        if (!$this->model->where('id', $params['id'])->update($form)) {
            return AppResult::response201('操作失败');
        }

        return AppResult::response200('操作成功');
    }

    /**
     * 修改分类
     * @return string
     */
    public function type()
    {
        $params = $this->params;
        if (!isset($params['id']) || !isset($params['type_id'])) {
            return AppResult::response203('操作超时！');
        }

        $form['type_id']    = $params['type_id'];
        $form['updated_at'] = time();

        if (!$this->model->where('id', $params['id'])->update($form)) {
            return AppResult::response201('操作失败');
        }

        return AppResult::response200('操作成功');
    }

    /**
     * 列表单页配置
     * @return string
     */
    public function list_page()
    {
        $params = $this->params;
        if(empty($params['__table']))
        {
            return AppResult::response201('数据编辑失败，请稍后再试！');
        }

        $_table = $params['__table'];
        $params = DataUtil::field($params, ['__table']);
        $params = json_encode($params, JSON_UNESCAPED_UNICODE);

        if(AdminSetupModel::query()->where('table', $_table)->exists())
        {
            AdminSetupModel::query()->where('table', $_table)->update(['value'=>$params]);
        } else {
            AdminSetupModel::query()->where('table', $_table)->insert(['table'=>$_table, 'value'=>$params]);
        }

        Cache::forget("ADMIN_SETUP_{$_table}");

        unset($_table, $params);

        return AppResult::response200('数据编辑成功！');
    }
}
